package handler

import (
	"net/http"

	"database/sql"

	"gitee.com/hp-huiw/family-expense-api/internal/dto"
	"gitee.com/hp-huiw/family-expense-api/internal/service"
	"gitee.com/hp-huiw/my-go-core/util"
	"github.com/gin-gonic/gin"
)

type JourneyHandler interface {
	QueryListByAccountGroup(ctx *gin.Context)
	Add(ctx *gin.Context)
	Update(ctx *gin.Context)
	Delete(ctx *gin.Context)
}

func NewJourneyHandler(db *sql.DB) JourneyHandler {
	return &journeyHandler{
		journeyService: service.NewJourneyService(db),
	}
}

// Matches /query-list-by-account-group of http get action.
func (h *journeyHandler) QueryListByAccountGroup(ctx *gin.Context) {
	pageSize, err := util.StringToInt64(ctx.Query("pageSize"))

	if err != nil {
		ctx.Error(err)
		return
	}

	pageIndex, err := util.StringToInt64(ctx.Query("pageIndex"))

	if err != nil {
		ctx.Error(err)
		return
	}

	c := ctx.Request.Context()
	accountGroupID := GetClaims(ctx).AccountGroupID
	result, err := h.journeyService.Query(c, accountGroupID, pageSize, pageIndex)

	if err != nil {
		ctx.Error(err)
		return
	}

	SendDataResponse(ctx, result)
}

// Matches /add of http post action.
func (h *journeyHandler) Add(ctx *gin.Context) {
	var postedData dto.JourneyRequest

	if err := ctx.ShouldBindJSON(&postedData); err != nil {
		ctx.Error(err)
		return
	}

	c := ctx.Request.Context()
	accountGroupID := GetClaims(ctx).AccountGroupID
	err := h.journeyService.Add(c, accountGroupID, &postedData)

	if err != nil {
		ctx.Error(err)
		return
	}

	SendStatusResponse(ctx, http.StatusNoContent)
}

// Matches /update of http post action.
func (h *journeyHandler) Update(ctx *gin.Context) {
	var postedData dto.JourneyRequest

	if err := ctx.ShouldBindJSON(&postedData); err != nil {
		ctx.Error(err)
		return
	}

	c := ctx.Request.Context()
	accountGroupID := GetClaims(ctx).AccountGroupID
	err := h.journeyService.Update(c, accountGroupID, &postedData)

	if err != nil {
		ctx.Error(err)
		return
	}

	SendStatusResponse(ctx, http.StatusNoContent)
}

// Matches /delete of http post action.
func (h *journeyHandler) Delete(ctx *gin.Context) {
	var postedData struct {
		ID string `json:"id"`
	}

	if err := ctx.ShouldBindJSON(&postedData); err != nil {
		ctx.Error(err)
		return
	}

	c := ctx.Request.Context()
	accountGroupID := GetClaims(ctx).AccountGroupID
	result, err := h.journeyService.Delete(c, accountGroupID, postedData.ID)

	if err != nil {
		ctx.Error(err)
		return
	}

	SendDataResponse(ctx, result)
}

// Container of JourneyHandler functions.
type journeyHandler struct {
	journeyService service.JourneyService
}
